








//
//  AddNewEquipmentViewController.m
//  nncloud
//
//  Created by macfeel on 2019/5/29.
//  Copyright © 2019 macfai. All rights reserved.
//
#import "UICustomDatePicker.h"
#import "AddNewEquipmentViewController.h"
#import "EquipmentListViewController.h"
#import "FacturerListViewController.h"
#import "EditToFillViewController.h"
#import "GuiGeXinghaoViewController.h"

@interface AddNewEquipmentViewController ()

<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *dataArray;
//@property (nonatomic,strong)NSMutableArray *titleArray;
@property (nonatomic,strong)NSMutableArray *dictArray;

//@property (nonatomic,strong)NSMutableArray *equipArray;

@property (nonatomic,assign)NSInteger currentRow;
//
@property(nonatomic,strong)NSArray *nameArray;

///接收字典
@property(nonatomic,strong)NSDictionary *dict;

//
//@property(nonatomic,strong)NSArray *rightArray;
@property(nonatomic,assign)BOOL isDate;

///标记器材种类
@property(nonatomic,assign)BOOL isQicaiType;

///标记设备型号
@property(nonatomic,assign)BOOL isShebeiXinghao;

///标记厂家
@property(nonatomic,assign)BOOL isFactory;

///日期字符串
@property(nonatomic,copy)NSString *dateString;

///器材字符串
@property(nonatomic,copy)NSString *qicaiString;

///厂家字符串
@property(nonatomic,copy)NSString *factrotyString;

///设备型号字符串
@property(nonatomic,copy)NSString *shebeiXinghaoString;


///编辑的填写的内容
@property(nonatomic,copy)NSString *content;


@end

@implementation AddNewEquipmentViewController

#define cellIdentifier  @"relayd"
//#define HeaderHight  290
#define PageSize 20

-(UITableView *)tableView{
    
    if (!_tableView) {
        
        WeakStament(ws);
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0 , 0, ScreenWidth , ScreenHeight - ScreenHeightFlex) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 55;
        //        _tableView.separatorColor = [UIColor clearColor];
        _tableView.backgroundColor = kBackgroundColor;
        //        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellIdentifier];
        //        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //            [ws loadData];
        //        }];
        //        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        //            [ws loadMoreData];
        //        }];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.tableFooterView = [UIView new];
        
    }
    return _tableView;
}
- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.currentRow = -1;
    self.dataArray = [NSMutableArray array];
    //    self.titleArray = [NSMutableArray array];
//    self.equipArray = [NSMutableArray array];
    
    [self.navigationItem setItemWithTitle:@"新增设备" textColor:kNavigationTitleColor fontSize:18 itemType:center];
    
    [self addNavgationRightButtonWithFrame:CGRectMake(0, 0, 30, 30) title:@"确认新增" Image:@"" selectedIMG:@"" tartget:self action:@selector(sureAction)];
    
    [self.view addSubview:self.tableView];

   
    ///标记是否是日期
    self.isDate = NO;
    self.isQicaiType = NO;
    self.isFactory = NO;
    ///接收上个页面传过来的字典进行数据展示
    [self formData];
    
    ///下面的格式是写死的数据格式
//     [self loadTitleArray];
    
}

///进行数据处理
-(void)formData{
    
    NSDictionary *dict;
    if (self.model) {
        ///传过来的模型转成字典
        dict = [self.model mj_keyValues];
        YYLog(@"为什么这么少heheh:%@",dict);
        self.dict = dict;
        YYLog(@"%@",dict);
    }
    
    NSArray *dictArray = [self.dict allKeys];
    self.titleArray = [dictArray copy];
    //    NSDictionary *dict = self.dict;
    for (int i=0; i<[dict allKeys].count; i++) {
        NSString *key = dictArray[i];
        NSString *value = [dict objectForKey:key];
        //处理null
        if ([value isKindOfClass:[NSNull class]]) {
            value = @"";
        }
        //处理返回的int 类型  因为赋值时候需要进行字符串赋值
        if ([value isKindOfClass:[NSNumber class]]) {
            value = [NSString stringWithFormat:@"%@",value];
        }
        ////全部处理成空字符串，这样就可以和编辑页面用一样的逻辑来处理了，进行空串的替换，因为数组中的空串也是有效的，也是数组的对象
        
        if ([value isKindOfClass:[NSString class]]) {
            value = @"";
        }
        
        [self.dataArray addObject:value];
       
    }
    YYLog(@"%lu",(unsigned long)self.dataArray.count);
    [self.tableView reloadData];
}


///加载左侧标题
-(void)loadTitleArray{
    
    if ([self.flag isEqualToString:@"r"]) {
        self.nameArray = @[@"段编号",@"器材种类",@"型号",@"生产厂家",@"周期",@"组合位置",@"入所次数",@"返所原因",@"验收次数",@"出厂日期",@"入所日期",@"检修日期",@"验收日期",@"出所日期",@"到期日期",@"预检员",@"检修员",@"验收员",@"厂编号",@"站名",@"报废日期",@"测试数据表编号",@"使用处所",@"备注"];
    
    }else if ([self.flag isEqualToString:@"s"]){
        self.nameArray = @[@"设备编号",@"设备种类",@"设备型号",@"生产厂家",@"出所日期",@"到期日期",@"去向",@"岔号",@"牵引名称",@"线制",@"开向",@"表示杆特征",@"设备老编号",@"出厂编号",@"出厂日期",@"检修日期",@"验收日期",@"整机检修人",@"整机眼收人",@"备注"];
    }else{
    
        self.nameArray = @[@"段编号",@"器材种类",@"型号",@"生产厂家",@"厂编号",@"站名",@"使用位置",@"使用处所",@"用途",@"返所次数",@"返所原因",@"出厂日期",@"报废日期",@"入所日期",@"出所日期",@"检修日期",@"验收日期",@"到期日期",@"验收人",@"检修人",@"状态",@"抽验人",@"备注"];
    }

}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    ///这个是从输入页面回来后在这里替换掉数组中被修改的元素
//    if ( [NUserModel shareInstance].isClickedEdit == YES) {
//
//        [self updateDataSource];
//        [NUserModel shareInstance].isClickedEdit = false;
//    }
}
#pragma mark 将修改后的数据更新到数据源数组中
///将修改后的数据更新到数据源数组中
-(void)updateDataSource{
    ////注意 对于不可变数组必须是 mutableCopy 深拷贝 如果是copy 就直接挂掉了
    NSMutableArray *newArray = [self.dataArray mutableCopy];
    if (self.isDate==YES) {
        ///选择日期
        [newArray replaceObjectAtIndex:self.currentRow withObject:self.dateString?:@""];
        
    }else if (self.isQicaiType==YES){
        ///器材种类  是针对继电器来说的
        [newArray replaceObjectAtIndex:self.currentRow withObject:self.qicaiString?:@""];
        
    }else if (self.isShebeiXinghao==YES){
        
        ///选择厂家过来的
        [newArray replaceObjectAtIndex:self.currentRow withObject:self.shebeiXinghaoString?:@""];
        
    }else if (self.isFactory==YES){
        
        ///选择厂家过来的
        [newArray replaceObjectAtIndex:self.currentRow withObject:self.factrotyString?:@""];
        
    }else{
        
        ///是从编辑填写页面进来后走的分之
        [newArray replaceObjectAtIndex:self.currentRow withObject:self.content?:@""];
    }
    
    self.dataArray = newArray;
    [self.tableView reloadData];
    ////刷新某一行
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:self.currentRow inSection:0];
    YYLog(@"当前行数：%ld",(long)self.currentRow);
    //组数中的cell
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
}


///更新日期到数据源
-(void)updateDateToDataSource{
    [self updateDataSource];
    self.isDate = false;
}


#pragma mark - 确认新增
///确认
-(void)sureAction{
    //    NSDictionary *dic = @{@"段编号":@"00070517096",@"验收次数":@"1",@"报废原因":@"年久失修"};
    //    NSDictionary *dict = @{@"data":[dic mj_JSONString],@"method":@"1"};
    
    NSString *url;
    
    if ([[NUserModel shareInstance].equipType isEqualToString:@"r"]) {
        url = kupdateUrl;
    }else if ([[NUserModel shareInstance].equipType isEqualToString:@"s"]){
        url = kupdateSwitchUrl;
    }else if ([[NUserModel shareInstance].equipType isEqualToString:@"s"]){
        url = kupdateCMUrl;
    }else{
        url = kupdateCamelUrl;
    }
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    for (int i=0; i<self.titleArray.count; i++) {
        [dic setObject:self.dataArray[i] forKey:self.titleArray[i]];
    }
    
    ///method  1 修改    3新增    2复制添加暂时不做
    NSDictionary *dict = @{@"data":[dic mj_JSONString],@"method":@"3"};
    [NNetworkClient postRequestWithBaseUrl:url setParameters:dict success:^(id responseObject) {
        if ([responseObject[@"errorCode"]integerValue]==0) {
            [AFToast showText:@"新增成功"];
        }
        [self.navigationController popViewControllerAnimated:YES];
    } fail:^(NSError *error) {
        
    } delegater:nil];
}



#pragma mark - tableView   delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //    return self.leftArray.count;
//    NSDictionary *dict = self.dict;
//    return [dict allKeys].count;
        return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //NSDictionary *dict = self.dict;
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    // Configure the cell...
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleValue1
                                      reuseIdentifier: cellIdentifier];
    }
    cell.selectionStyle = 0;
    cell.textLabel.textColor = kDarkGrayColor;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//    cell.textLabel.text = self.nameArray[indexPath.row];
    
    cell.textLabel.text = self.titleArray[indexPath.row];
    cell.detailTextLabel.text = self.dataArray[indexPath.row];
    
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ///点击哪一行进去，还要记录当前的索引，返回的时候刷新刚才点击的那一行
    self.currentRow = indexPath.row;
    
    ///点击进去进行编辑
//    self.currentRow = indexPath.row;
    
    ///点击进去进行编辑
    
    NSString *titleString = self.titleArray[indexPath.row];
    
    if ([titleString containsString:@"日期"]) {
        
        [UICustomDatePicker showCustomDatePickerAtView:self.view choosedDateBlock:^(NSDate *date) {
            NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
            fmt.dateFormat = @"yyyy-MM-dd";
            NSString *string = [fmt stringFromDate:date];
            YYLog(@"current Date:%@",string);
            ///将选择的时间放到数据源中
            self.dateString = string;
            self.isDate = YES;
            [self updateDateToDataSource];
            
        } cancelBlock:^{
            
        }];
        
    }else if([titleString containsString:@"器材种类"]||[titleString containsString:@"设备种类"]){
        
        ///继电器 叫器材种类   转辙机 叫设备种类
        //进入继电器类型列表
        self.isQicaiType = YES;
        EquipmentListViewController *equip = [EquipmentListViewController new];
        ///拿到器材种类
        equip.block = ^(NSString * _Nonnull type) {
            YYLog(@"%@",type);
            self.qicaiString = type;
            [self updateDataSource];
            self.isQicaiType = false;
        };
        [self.navigationController pushViewController:equip animated:YES];
        
    }else if([titleString containsString:@"厂家"]){
        //进入继电器类型列表
        self.isFactory = YES;
        FacturerListViewController *equip = [FacturerListViewController new];
        equip.block = ^(NSString * _Nonnull name) {
            YYLog(@"%@",name);
            self.factrotyString = name;
            [self updateDataSource];
            self.isFactory = false;
        };
        [self.navigationController pushViewController:equip animated:YES];
        
    }else if([titleString containsString:@"型号"]){
        ///专门针对继电器来说
        //进入继电器类型列表  继电器叫型号  转辙机叫 设备型号
        self.isShebeiXinghao = YES;
        GuiGeXinghaoViewController *equip = [GuiGeXinghaoViewController new];
        equip.block = ^(NSString * _Nonnull xinghao) {
            self.shebeiXinghaoString = xinghao;
            [self updateDataSource];
            self.isShebeiXinghao = false;
        };
        [self.navigationController pushViewController:equip animated:YES];
        
    }else{
        
        ///继电器 转辙机共用
        ///输入框进行编辑
        EditToFillViewController *fill = [EditToFillViewController new];
        fill.block = ^(NSString * _Nonnull content) {
            YYLog(@"%@",content);
            self.content = content;
            [self updateDataSource];
        };
        [self.navigationController pushViewController:fill animated:YES];
        
    }
}

@end
